package com.fingard.dsp.bank.directbank.mhcbc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Alon on 2019-10-21.
 * @version 1.0
 */
public class MHCBC01Transaction extends MHCBC01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int compareDay = DateHelper.compareDay(tmpCalendarTo.getTime(), tmpCalendarFrom.getTime());
            if (compareDay == -1) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("查询交易终止日期小于查询交易起始日期!");
                retAts.writeEnd();
                return retAts;
            }
            Calendar tmpCalendarTemp = Calendar.getInstance();
            tmpCalendarTemp.setTime(p_req7516.getDateFrom());
            //30天间隔查询一次
            while (DateHelper.compareDay(tmpCalendarTo.getTime(), tmpCalendarTemp.getTime()) >= 0) {
                String startDate = "";
                String endDate = "";
                tmpCalendarFrom.setTime(tmpCalendarTemp.getTime());
                startDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
                tmpCalendarTemp.setTime(DateHelper.addDays(tmpCalendarFrom.getTime(), 30));

                if (DateHelper.compareDay(tmpCalendarTo.getTime(), tmpCalendarTemp.getTime()) > 0) {
                    endDate = Format.Date8Format.format(tmpCalendarTemp.getTime());
                } else {
                    endDate = Format.Date8Format.format(tmpCalendarTo.getTime());
                }
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("trn-qrydtl-rq");
                xmlWriter.writeElementString("seqno", Format.DateTime17SSSFormat.format(new Date()).substring(1));
                xmlWriter.writeStartElement("qrydtl-rq");
                xmlWriter.writeElementString("eid", bankFront.org);//企业代码
                xmlWriter.writeElementString("opno", bankFront.operator);//操作员代码
                xmlWriter.writeElementString("actno", p_req7516.actNum);//账号
                xmlWriter.writeElementString("start_date", startDate);//查询帐户明细的起始交易日期
                xmlWriter.writeElementString("end_date", endDate);//查询帐户明细的终止交易日期，查询起止交易时间不超过30天
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/edes/msg-xdata/trn-qrydtl-rs/qrydtl-rs/retcode");
                        if (returnCode != null && "0000".equals(returnCode)) {
                            while (tmpBkReader.read("/edes/msg-xdata/trn-qrydtl-rs/qrydtl-rs/qryactno-dtl")) {
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                XElement tmpRecord = tmpBkReader.readedXElement;

                                tmpRetDetail.actArea = p_req7516.actArea;
                                tmpRetDetail.actNum = p_req7516.actNum;//查询的账号
                                String tranDate = tmpRecord.getSingleText("vdate");
                                tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";

                                Double tranAmt = Double.parseDouble(tmpRecord.getSingleText("amount"));//返回交易金额，无小数点精确到分,固定14位不足高位补0
                                DecimalFormat df = new DecimalFormat();
                                String style = "0.00";
                                df.applyPattern(style);
                                tmpRetDetail.tranAmt = df.format(tranAmt / 100.00);

                                tmpRetDetail.cdFlag = "";//借贷标志
                                String cdFlag = tmpRecord.getSingleText("crdb");//借贷标记
                                if ("D".equals(cdFlag) || "RD".equals(cdFlag)) {
                                    //支出
                                    tmpRetDetail.recAccNum = tmpRecord.getSingleText("payee_info/payee_actno");//对方账号
                                    tmpRetDetail.recAccName = tmpRecord.getSingleText("payee_info/payee_name");//对方账号名
                                    tmpRetDetail.recAccBank = tmpRecord.getSingleText("payee_info/payee_brname");//对方行号
                                    tmpRetDetail.cdFlag = "1";
                                } else if ("C".equals(cdFlag) || "RC".equals(cdFlag)) {
                                    //收入
                                    tmpRetDetail.recAccNum = tmpRecord.getSingleText("payer_info/payer_actno");//对方账号
                                    tmpRetDetail.recAccName = tmpRecord.getSingleText("payer_info/payer_name");//对方账号名
                                    tmpRetDetail.recAccBank = tmpRecord.getSingleText("payer_info/payer_brname");//对方行号
                                    tmpRetDetail.cdFlag = "2";
                                }
                                tmpRetDetail.usage = tmpRecord.getSingleText("usage");//用途
//                                tmpRetDetail.askNumber = tmpRecord.getSingleText("rsv1");//支付流水号？？
                                tmpRetDetail.cur = "1";//币种
                                tmpRetDetail.originator = tmpRecord.getSingleText("refno");//银行返回流水号
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            if (!StringHelper.isNullOrEmpty(convertRespToBank(returnCode))) {
                                if ("0012".equals(returnCode)) {//当前30天内查询无记录，则继续查询
                                    tmpRespCode = "0";
                                    continue;
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "查询起始日期：" + startDate + " 查询终止日期：" + endDate + " 银行返回信息：" + returnCode + convertRespToBank(returnCode);
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = "查询起始日期：" + startDate + " 查询终止日期：" + endDate + " 错误代码未映射，错误代码：" + returnCode;
                            }
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用历史余额查询
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
